#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
工具栏管理器模块
提供自定义工具栏按钮功能
"""

import json
import os
from PyQt6.QtWidgets import (
    QToolBar, QWidget, QHBoxLayout, QVBoxLayout, 
    QPushButton, QLabel, QComboBox, QSpinBox, QCheckBox,
    QDialog, QDialogButtonBox, QListWidget, QListWidgetItem,
    QGroupBox, QFormLayout, QLineEdit, QTextEdit, QFileDialog,
    QMessageBox, QSplitter, QFrame
)
from PyQt6.QtCore import Qt, QObject, pyqtSignal, QSize
from PyQt6.QtGui import QIcon, QPixmap, QAction, QFont

class ToolbarAction:
    """工具栏动作类"""
    
    def __init__(self, action_id, name, icon_path=None, tooltip="", shortcut="", callback=None, separator=False):
        self.action_id = action_id
        self.name = name
        self.icon_path = icon_path
        self.tooltip = tooltip
        self.shortcut = shortcut
        self.callback = callback
        self.separator = separator
        self.enabled = True
        self.visible = True
    
    def to_dict(self):
        """转换为字典"""
        return {
            "action_id": self.action_id,
            "name": self.name,
            "icon_path": self.icon_path,
            "tooltip": self.tooltip,
            "shortcut": self.shortcut,
            "separator": self.separator,
            "enabled": self.enabled,
            "visible": self.visible
        }
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建"""
        action = cls(
            data["action_id"],
            data["name"],
            data.get("icon_path"),
            data.get("tooltip", ""),
            data.get("shortcut", "")
        )
        action.separator = data.get("separator", False)
        action.enabled = data.get("enabled", True)
        action.visible = data.get("visible", True)
        return action

class ToolbarCustomizationDialog(QDialog):
    """工具栏自定义对话框"""
    
    def __init__(self, toolbar_manager, parent=None):
        super().__init__(parent)
        self.toolbar_manager = toolbar_manager
        self.setWindowTitle("自定义工具栏")
        self.setModal(True)
        self.resize(800, 600)
        
        self.setup_ui()
        self.load_data()
    
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        # 创建分割器
        splitter = QSplitter(Qt.Orientation.Horizontal)
        layout.addWidget(splitter)
        
        # 左侧：可用动作列表
        left_frame = QFrame()
        left_layout = QVBoxLayout(left_frame)
        
        left_layout.addWidget(QLabel("可用动作:"))
        self.available_list = QListWidget()
        self.available_list.setDragDropMode(QListWidget.DragDropMode.DragOnly)
        left_layout.addWidget(self.available_list)
        
        # 添加自定义动作按钮
        add_custom_btn = QPushButton("添加自定义动作")
        add_custom_btn.clicked.connect(self.add_custom_action)
        left_layout.addWidget(add_custom_btn)
        
        splitter.addWidget(left_frame)
        
        # 右侧：当前工具栏配置
        right_frame = QFrame()
        right_layout = QVBoxLayout(right_frame)
        
        # 工具栏选择
        toolbar_layout = QHBoxLayout()
        toolbar_layout.addWidget(QLabel("工具栏:"))
        self.toolbar_combo = QComboBox()
        self.toolbar_combo.currentTextChanged.connect(self.on_toolbar_changed)
        toolbar_layout.addWidget(self.toolbar_combo)
        
        add_toolbar_btn = QPushButton("新建工具栏")
        add_toolbar_btn.clicked.connect(self.add_new_toolbar)
        toolbar_layout.addWidget(add_toolbar_btn)
        
        remove_toolbar_btn = QPushButton("删除工具栏")
        remove_toolbar_btn.clicked.connect(self.remove_toolbar)
        toolbar_layout.addWidget(remove_toolbar_btn)
        
        right_layout.addLayout(toolbar_layout)
        
        right_layout.addWidget(QLabel("当前工具栏动作:"))
        self.current_list = QListWidget()
        self.current_list.setDragDropMode(QListWidget.DragDropMode.DropOnly)
        self.current_list.setAcceptDrops(True)
        right_layout.addWidget(self.current_list)
        
        # 动作控制按钮
        action_buttons_layout = QHBoxLayout()
        
        move_up_btn = QPushButton("上移")
        move_up_btn.clicked.connect(self.move_action_up)
        action_buttons_layout.addWidget(move_up_btn)
        
        move_down_btn = QPushButton("下移")
        move_down_btn.clicked.connect(self.move_action_down)
        action_buttons_layout.addWidget(move_down_btn)
        
        add_separator_btn = QPushButton("添加分隔符")
        add_separator_btn.clicked.connect(self.add_separator)
        action_buttons_layout.addWidget(add_separator_btn)
        
        remove_action_btn = QPushButton("移除")
        remove_action_btn.clicked.connect(self.remove_action)
        action_buttons_layout.addWidget(remove_action_btn)
        
        right_layout.addLayout(action_buttons_layout)
        
        splitter.addWidget(right_frame)
        
        # 对话框按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | 
            QDialogButtonBox.StandardButton.Cancel |
            QDialogButtonBox.StandardButton.Reset
        )
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        button_box.button(QDialogButtonBox.StandardButton.Reset).clicked.connect(self.reset_to_default)
        layout.addWidget(button_box)
    
    def load_data(self):
        """加载数据"""
        # 加载可用动作
        self.available_list.clear()
        for action in self.toolbar_manager.get_available_actions():
            item = QListWidgetItem(action.name)
            item.setData(Qt.ItemDataRole.UserRole, action.action_id)
            if action.icon_path and os.path.exists(action.icon_path):
                item.setIcon(QIcon(action.icon_path))
            self.available_list.addItem(item)
        
        # 加载工具栏列表
        self.toolbar_combo.clear()
        for toolbar_id in self.toolbar_manager.get_toolbar_ids():
            self.toolbar_combo.addItem(toolbar_id)
        
        # 加载当前工具栏
        if self.toolbar_combo.count() > 0:
            self.on_toolbar_changed(self.toolbar_combo.currentText())
    
    def on_toolbar_changed(self, toolbar_id):
        """工具栏改变事件"""
        self.current_list.clear()
        actions = self.toolbar_manager.get_toolbar_actions(toolbar_id)
        
        for action in actions:
            if action.separator:
                item = QListWidgetItem("--- 分隔符 ---")
            else:
                item = QListWidgetItem(action.name)
                if action.icon_path and os.path.exists(action.icon_path):
                    item.setIcon(QIcon(action.icon_path))
            
            item.setData(Qt.ItemDataRole.UserRole, action.action_id)
            self.current_list.addItem(item)
    
    def add_custom_action(self):
        """添加自定义动作"""
        dialog = CustomActionDialog(self)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            action_data = dialog.get_action_data()
            action = ToolbarAction(
                action_data["id"],
                action_data["name"],
                action_data["icon"],
                action_data["tooltip"],
                action_data["shortcut"]
            )
            self.toolbar_manager.add_custom_action(action)
            self.load_data()
    
    def add_new_toolbar(self):
        """添加新工具栏"""
        from PyQt6.QtWidgets import QInputDialog
        
        toolbar_id, ok = QInputDialog.getText(self, "新建工具栏", "工具栏ID:")
        if ok and toolbar_id:
            if self.toolbar_manager.create_toolbar(toolbar_id):
                self.toolbar_combo.addItem(toolbar_id)
                self.toolbar_combo.setCurrentText(toolbar_id)
            else:
                QMessageBox.warning(self, "警告", "工具栏ID已存在")
    
    def remove_toolbar(self):
        """删除工具栏"""
        current_toolbar = self.toolbar_combo.currentText()
        if current_toolbar and current_toolbar not in ["main", "file", "edit", "view"]:
            reply = QMessageBox.question(self, "确认", f"确定要删除工具栏 '{current_toolbar}' 吗？")
            if reply == QMessageBox.StandardButton.Yes:
                self.toolbar_manager.remove_toolbar(current_toolbar)
                self.toolbar_combo.removeItem(self.toolbar_combo.currentIndex())
    
    def move_action_up(self):
        """上移动作"""
        current_row = self.current_list.currentRow()
        if current_row > 0:
            item = self.current_list.takeItem(current_row)
            self.current_list.insertItem(current_row - 1, item)
            self.current_list.setCurrentRow(current_row - 1)
    
    def move_action_down(self):
        """下移动作"""
        current_row = self.current_list.currentRow()
        if current_row < self.current_list.count() - 1:
            item = self.current_list.takeItem(current_row)
            self.current_list.insertItem(current_row + 1, item)
            self.current_list.setCurrentRow(current_row + 1)
    
    def add_separator(self):
        """添加分隔符"""
        item = QListWidgetItem("--- 分隔符 ---")
        item.setData(Qt.ItemDataRole.UserRole, "separator")
        self.current_list.addItem(item)
    
    def remove_action(self):
        """移除动作"""
        current_row = self.current_list.currentRow()
        if current_row >= 0:
            self.current_list.takeItem(current_row)
    
    def reset_to_default(self):
        """重置为默认"""
        reply = QMessageBox.question(self, "确认", "确定要重置所有工具栏为默认配置吗？")
        if reply == QMessageBox.StandardButton.Yes:
            self.toolbar_manager.reset_to_default()
            self.load_data()
    
    def accept(self):
        """确认"""
        # 保存当前工具栏配置
        toolbar_id = self.toolbar_combo.currentText()
        if toolbar_id:
            actions = []
            for i in range(self.current_list.count()):
                item = self.current_list.item(i)
                action_id = item.data(Qt.ItemDataRole.UserRole)
                if action_id == "separator":
                    action = ToolbarAction(f"sep_{i}", "", separator=True)
                else:
                    action = self.toolbar_manager.get_action_by_id(action_id)
                if action:
                    actions.append(action)
            
            self.toolbar_manager.set_toolbar_actions(toolbar_id, actions)
        
        super().accept()

class CustomActionDialog(QDialog):
    """自定义动作对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("添加自定义动作")
        self.setModal(True)
        self.resize(400, 300)
        
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        form_layout = QFormLayout()
        
        self.id_edit = QLineEdit()
        form_layout.addRow("动作ID:", self.id_edit)
        
        self.name_edit = QLineEdit()
        form_layout.addRow("显示名称:", self.name_edit)
        
        icon_layout = QHBoxLayout()
        self.icon_edit = QLineEdit()
        icon_browse_btn = QPushButton("浏览...")
        icon_browse_btn.clicked.connect(self.browse_icon)
        icon_layout.addWidget(self.icon_edit)
        icon_layout.addWidget(icon_browse_btn)
        form_layout.addRow("图标路径:", icon_layout)
        
        self.tooltip_edit = QLineEdit()
        form_layout.addRow("工具提示:", self.tooltip_edit)
        
        self.shortcut_edit = QLineEdit()
        form_layout.addRow("快捷键:", self.shortcut_edit)
        
        layout.addLayout(form_layout)
        
        # 对话框按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | 
            QDialogButtonBox.StandardButton.Cancel
        )
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
    
    def browse_icon(self):
        """浏览图标"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择图标", "", 
            "图像文件 (*.png *.jpg *.jpeg *.gif *.bmp *.ico *.svg)"
        )
        if file_path:
            self.icon_edit.setText(file_path)
    
    def get_action_data(self):
        """获取动作数据"""
        return {
            "id": self.id_edit.text(),
            "name": self.name_edit.text(),
            "icon": self.icon_edit.text(),
            "tooltip": self.tooltip_edit.text(),
            "shortcut": self.shortcut_edit.text()
        }

class ToolbarManager(QObject):
    """工具栏管理器"""
    
    # 信号定义
    toolbar_changed = pyqtSignal(str)  # 工具栏改变信号
    
    def __init__(self, main_window):
        super().__init__()
        self.main_window = main_window
        self.config_file = os.path.join(os.path.expanduser("~"), ".gofile", "toolbar_config.json")
        
        # 确保配置目录存在
        os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
        
        # 工具栏实例
        self.toolbars = {}
        
        # 可用动作
        self.available_actions = {}
        
        # 工具栏配置
        self.toolbar_configs = {
            "main": {
                "name": "主工具栏",
                "position": "top",
                "movable": True,
                "actions": ["new", "open", "save", "separator", "undo", "redo", "separator", "cut", "copy", "paste"]
            },
            "file": {
                "name": "文件工具栏",
                "position": "top",
                "movable": True,
                "actions": ["new", "open", "open_folder", "save", "save_as"]
            },
            "edit": {
                "name": "编辑工具栏",
                "position": "top",
                "movable": True,
                "actions": ["undo", "redo", "separator", "cut", "copy", "paste", "separator", "find", "replace"]
            },
            "view": {
                "name": "视图工具栏",
                "position": "top",
                "movable": True,
                "actions": ["zoom_in", "zoom_out", "zoom_reset", "separator", "fullscreen"]
            }
        }
        
        # 初始化默认动作
        self.init_default_actions()
        
        # 加载配置
        self.load_config()
    
    def init_default_actions(self):
        """初始化默认动作"""
        default_actions = [
            ToolbarAction("new", "新建", tooltip="新建文件", shortcut="Ctrl+N"),
            ToolbarAction("open", "打开", tooltip="打开文件", shortcut="Ctrl+O"),
            ToolbarAction("open_folder", "打开文件夹", tooltip="打开文件夹", shortcut="Ctrl+Shift+O"),
            ToolbarAction("save", "保存", tooltip="保存文件", shortcut="Ctrl+S"),
            ToolbarAction("save_as", "另存为", tooltip="另存为", shortcut="Ctrl+Shift+S"),
            ToolbarAction("undo", "撤销", tooltip="撤销", shortcut="Ctrl+Z"),
            ToolbarAction("redo", "重做", tooltip="重做", shortcut="Ctrl+Y"),
            ToolbarAction("cut", "剪切", tooltip="剪切", shortcut="Ctrl+X"),
            ToolbarAction("copy", "复制", tooltip="复制", shortcut="Ctrl+C"),
            ToolbarAction("paste", "粘贴", tooltip="粘贴", shortcut="Ctrl+V"),
            ToolbarAction("find", "查找", tooltip="查找", shortcut="Ctrl+F"),
            ToolbarAction("replace", "替换", tooltip="替换", shortcut="Ctrl+H"),
            ToolbarAction("zoom_in", "放大", tooltip="放大", shortcut="Ctrl++"),
            ToolbarAction("zoom_out", "缩小", tooltip="缩小", shortcut="Ctrl+-"),
            ToolbarAction("zoom_reset", "重置缩放", tooltip="重置缩放", shortcut="Ctrl+0"),
            ToolbarAction("fullscreen", "全屏", tooltip="切换全屏", shortcut="F11"),
            ToolbarAction("play_pause", "播放/暂停", tooltip="播放/暂停", shortcut="Space"),
            ToolbarAction("stop", "停止", tooltip="停止播放", shortcut="Ctrl+."),
            ToolbarAction("previous", "上一个", tooltip="上一个文件", shortcut="Ctrl+Left"),
            ToolbarAction("next", "下一个", tooltip="下一个文件", shortcut="Ctrl+Right"),
        ]
        
        for action in default_actions:
            self.available_actions[action.action_id] = action
    
    def create_toolbar(self, toolbar_id, name=None, position="top"):
        """创建工具栏"""
        if toolbar_id in self.toolbars:
            return False
        
        toolbar = QToolBar(name or toolbar_id, self.main_window)
        toolbar.setMovable(True)
        toolbar.setVisible(False)  # 默认隐藏工具栏
        toolbar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon)
        
        # 添加到主窗口
        if position == "top":
            self.main_window.addToolBar(Qt.ToolBarArea.TopToolBarArea, toolbar)
        elif position == "bottom":
            self.main_window.addToolBar(Qt.ToolBarArea.BottomToolBarArea, toolbar)
        elif position == "left":
            self.main_window.addToolBar(Qt.ToolBarArea.LeftToolBarArea, toolbar)
        elif position == "right":
            self.main_window.addToolBar(Qt.ToolBarArea.RightToolBarArea, toolbar)
        
        self.toolbars[toolbar_id] = toolbar
        
        # 添加到配置
        if toolbar_id not in self.toolbar_configs:
            self.toolbar_configs[toolbar_id] = {
                "name": name or toolbar_id,
                "position": position,
                "movable": True,
                "actions": []
            }
        
        return True
    
    def remove_toolbar(self, toolbar_id):
        """移除工具栏"""
        if toolbar_id in ["main", "file", "edit", "view"]:
            return False  # 不能删除内置工具栏
        
        if toolbar_id in self.toolbars:
            toolbar = self.toolbars[toolbar_id]
            self.main_window.removeToolBar(toolbar)
            del self.toolbars[toolbar_id]
            
            if toolbar_id in self.toolbar_configs:
                del self.toolbar_configs[toolbar_id]
            
            self.save_config()
            return True
        return False
    
    def get_toolbar_ids(self):
        """获取工具栏ID列表"""
        return list(self.toolbar_configs.keys())
    
    def get_toolbar_actions(self, toolbar_id):
        """获取工具栏动作列表"""
        if toolbar_id not in self.toolbar_configs:
            return []
        
        actions = []
        action_ids = self.toolbar_configs[toolbar_id]["actions"]
        
        for action_id in action_ids:
            if action_id == "separator":
                action = ToolbarAction("separator", "", separator=True)
            elif action_id in self.available_actions:
                action = self.available_actions[action_id]
            else:
                continue
            actions.append(action)
        
        return actions
    
    def set_toolbar_actions(self, toolbar_id, actions):
        """设置工具栏动作"""
        if toolbar_id not in self.toolbar_configs:
            return False
        
        action_ids = []
        for action in actions:
            if action.separator:
                action_ids.append("separator")
            else:
                action_ids.append(action.action_id)
        
        self.toolbar_configs[toolbar_id]["actions"] = action_ids
        self.rebuild_toolbar(toolbar_id)
        self.save_config()
        return True
    
    def rebuild_toolbar(self, toolbar_id):
        """重建工具栏"""
        if toolbar_id not in self.toolbars:
            return
        
        toolbar = self.toolbars[toolbar_id]
        toolbar.clear()
        
        actions = self.get_toolbar_actions(toolbar_id)
        for action in actions:
            if action.separator:
                toolbar.addSeparator()
            else:
                qt_action = QAction(action.name, self.main_window)
                if action.icon_path and os.path.exists(action.icon_path):
                    qt_action.setIcon(QIcon(action.icon_path))
                if action.tooltip:
                    qt_action.setToolTip(action.tooltip)
                if action.shortcut:
                    qt_action.setShortcut(action.shortcut)
                
                qt_action.setEnabled(action.enabled)
                qt_action.setVisible(action.visible)
                
                # 连接回调函数
                if action.callback:
                    qt_action.triggered.connect(action.callback)
                elif hasattr(self.main_window, action.action_id):
                    callback = getattr(self.main_window, action.action_id)
                    if callable(callback):
                        qt_action.triggered.connect(callback)
                
                toolbar.addAction(qt_action)
    
    def get_available_actions(self):
        """获取可用动作列表"""
        return list(self.available_actions.values())
    
    def get_action_by_id(self, action_id):
        """根据ID获取动作"""
        return self.available_actions.get(action_id)
    
    def add_custom_action(self, action):
        """添加自定义动作"""
        self.available_actions[action.action_id] = action
        self.save_config()
    
    def remove_custom_action(self, action_id):
        """移除自定义动作"""
        # 检查是否为内置动作
        builtin_actions = ["new", "open", "open_folder", "save", "save_as", "undo", "redo", 
                          "cut", "copy", "paste", "find", "replace", "zoom_in", "zoom_out", 
                          "zoom_reset", "fullscreen", "play_pause", "stop", "previous", "next"]
        
        if action_id in builtin_actions:
            return False
        
        if action_id in self.available_actions:
            del self.available_actions[action_id]
            self.save_config()
            return True
        return False
    
    def show_customization_dialog(self):
        """显示自定义对话框"""
        dialog = ToolbarCustomizationDialog(self, self.main_window)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            # 重建所有工具栏
            for toolbar_id in self.toolbars.keys():
                self.rebuild_toolbar(toolbar_id)
            self.toolbar_changed.emit("all")
    
    def reset_to_default(self):
        """重置为默认配置"""
        # 重置工具栏配置
        self.toolbar_configs = {
            "main": {
                "name": "主工具栏",
                "position": "top",
                "movable": True,
                "actions": ["new", "open", "save", "separator", "undo", "redo", "separator", "cut", "copy", "paste"]
            },
            "file": {
                "name": "文件工具栏",
                "position": "top",
                "movable": True,
                "actions": ["new", "open", "open_folder", "save", "save_as"]
            },
            "edit": {
                "name": "编辑工具栏",
                "position": "top",
                "movable": True,
                "actions": ["undo", "redo", "separator", "cut", "copy", "paste", "separator", "find", "replace"]
            },
            "view": {
                "name": "视图工具栏",
                "position": "top",
                "movable": True,
                "actions": ["zoom_in", "zoom_out", "zoom_reset", "separator", "fullscreen"]
            }
        }
        
        # 重建所有工具栏
        for toolbar_id in self.toolbars.keys():
            self.rebuild_toolbar(toolbar_id)
        
        self.save_config()
    
    def add_action_to_toolbar(self, toolbar, text, callback, shortcut=None):
        """向工具栏添加动作"""
        action = QAction(text, self.main_window)
        if shortcut:
            action.setShortcut(shortcut)
        action.triggered.connect(callback)
        toolbar.addAction(action)
        return action
    
    def create_default_toolbar(self):
        """创建默认工具栏"""
        # 创建主工具栏
        toolbar_name = "主工具栏"
        if toolbar_name not in self.toolbars:
            main_toolbar = QToolBar(toolbar_name, self.main_window)
            main_toolbar.setMovable(True)
            main_toolbar.setVisible(False)  # 默认隐藏工具栏
            self.main_window.addToolBar(main_toolbar)
            self.toolbars[toolbar_name] = main_toolbar
        else:
            main_toolbar = self.toolbars[toolbar_name]
            main_toolbar.setVisible(False)  # 确保工具栏隐藏
        
        # 清空现有动作
        main_toolbar.clear()
        
        # 添加常用操作
        if hasattr(self.main_window, 'open_file'):
            self.add_action_to_toolbar(main_toolbar, "打开文件", self.main_window.open_file, "Ctrl+O")
        if hasattr(self.main_window, 'save_file'):
            self.add_action_to_toolbar(main_toolbar, "保存文件", self.main_window.save_file, "Ctrl+S")
        
        main_toolbar.addSeparator()
        
        if hasattr(self.main_window, 'zoom_in'):
            self.add_action_to_toolbar(main_toolbar, "放大", self.main_window.zoom_in, "Ctrl++")
        if hasattr(self.main_window, 'zoom_out'):
            self.add_action_to_toolbar(main_toolbar, "缩小", self.main_window.zoom_out, "Ctrl+-")
        
        return main_toolbar
    
    def save_config(self):
        """保存配置"""
        try:
            config = {
                "toolbar_configs": self.toolbar_configs,
                "custom_actions": {}
            }
            
            # 保存自定义动作
            builtin_actions = ["new", "open", "open_folder", "save", "save_as", "undo", "redo", 
                              "cut", "copy", "paste", "find", "replace", "zoom_in", "zoom_out", 
                              "zoom_reset", "fullscreen", "play_pause", "stop", "previous", "next"]
            
            for action_id, action in self.available_actions.items():
                if action_id not in builtin_actions:
                    config["custom_actions"][action_id] = action.to_dict()
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存工具栏配置失败: {e}")
    
    def create_toolbar_dialog(self):
        """创建工具栏设置对话框"""
        from PyQt6.QtWidgets import QMessageBox
        
        dialog = QDialog(self.main_window)
        dialog.setWindowTitle("工具栏设置")
        dialog.setFixedSize(600, 500)
        
        layout = QVBoxLayout()
        
        # 工具栏列表
        toolbar_group = QGroupBox("工具栏管理")
        toolbar_layout = QVBoxLayout()
        
        self.toolbar_list = QListWidget()
        for name in self.toolbars.keys():
            self.toolbar_list.addItem(name)
        toolbar_layout.addWidget(self.toolbar_list)
        
        # 工具栏操作按钮
        toolbar_btn_layout = QHBoxLayout()
        create_btn = QPushButton("创建工具栏")
        delete_btn = QPushButton("删除工具栏")
        toggle_btn = QPushButton("显示/隐藏")
        
        def create_toolbar():
            name = f"自定义工具栏_{len(self.toolbars) + 1}"
            toolbar = self.create_toolbar(name)
            self.toolbar_list.addItem(name)
            QMessageBox.information(dialog, "成功", f"工具栏 '{name}' 已创建！")
        
        def delete_toolbar():
            current_item = self.toolbar_list.currentItem()
            if current_item:
                toolbar_name = current_item.text()
                if toolbar_name in self.toolbars:
                    self.remove_toolbar(toolbar_name)
                    self.toolbar_list.takeItem(self.toolbar_list.row(current_item))
                    QMessageBox.information(dialog, "成功", f"工具栏 '{toolbar_name}' 已删除！")
        
        def toggle_toolbar():
            current_item = self.toolbar_list.currentItem()
            if current_item:
                toolbar_name = current_item.text()
                if toolbar_name in self.toolbars:
                    toolbar = self.toolbars[toolbar_name]
                    toolbar.setVisible(not toolbar.isVisible())
                    status = "显示" if toolbar.isVisible() else "隐藏"
                    QMessageBox.information(dialog, "成功", f"工具栏 '{toolbar_name}' 已{status}！")
        
        create_btn.clicked.connect(create_toolbar)
        delete_btn.clicked.connect(delete_toolbar)
        toggle_btn.clicked.connect(toggle_toolbar)
        
        toolbar_btn_layout.addWidget(create_btn)
        toolbar_btn_layout.addWidget(delete_btn)
        toolbar_btn_layout.addWidget(toggle_btn)
        
        toolbar_layout.addLayout(toolbar_btn_layout)
        toolbar_group.setLayout(toolbar_layout)
        layout.addWidget(toolbar_group)
        
        # 对话框按钮
        button_layout = QHBoxLayout()
        ok_btn = QPushButton("确定")
        cancel_btn = QPushButton("取消")
        
        def accept_dialog():
            self.save_config()
            dialog.accept()
        
        ok_btn.clicked.connect(accept_dialog)
        cancel_btn.clicked.connect(dialog.reject)
        
        button_layout.addWidget(ok_btn)
        button_layout.addWidget(cancel_btn)
        
        layout.addLayout(button_layout)
        dialog.setLayout(layout)
        
        return dialog
    
    def load_config(self):
        """加载配置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    
                    # 加载工具栏配置
                    if "toolbar_configs" in config:
                        self.toolbar_configs.update(config["toolbar_configs"])
                    
                    # 加载自定义动作
                    if "custom_actions" in config:
                        for action_id, action_data in config["custom_actions"].items():
                            action = ToolbarAction.from_dict(action_data)
                            self.available_actions[action_id] = action
        except Exception as e:
            print(f"加载工具栏配置失败: {e}")
    
    def initialize_toolbars(self):
        """初始化工具栏"""
        for toolbar_id, config in self.toolbar_configs.items():
            if self.create_toolbar(toolbar_id, config["name"], config["position"]):
                self.rebuild_toolbar(toolbar_id)